﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.UI;
using Pay.AliPay;
using Pay.WxPay;
using SingleUserMall.Actives;
using SingleUserMall.Authorization.Users;
using SingleUserMall.BargainItemDetail;
using SingleUserMall.Commissions;
using SingleUserMall.Coupons;
using SingleUserMall.Items;
using SingleUserMall.Logistics;
using SingleUserMall.Points;
using SingleUserMall.Refunds;
using SingleUserMall.ShoppingCarts;
using SingleUserMall.Stores;
using SingleUserMall.StoreSettings;
using SingleUserMall.Workers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static SingleUserMall.Commissions.Commission;
using static SingleUserMall.Items.Item;

namespace SingleUserMall.Orders
{
    public class OrderManager : DomainService
    {
        private readonly IRepository<Store> _storeRepository;
        private readonly IRepository<Order, long> _orderRepository;
        private readonly IRepository<OrderDetail, long> _orderDetailRepository;
        private readonly IRepository<UserCommission, long> _userCommisionRepository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<UserCoupon, long> _userCouponRepository;
        private readonly IRepository<GroupOrder, long> _groupOrderRepository;
        private readonly IRepository<GroupOrderDetail, long> _groupOrderDetailRepository;
        private readonly IRepository<Refund, long> _refundRepository;
        private readonly IRepository<UserCash, long> _userCashRepository;
        private readonly IRepository<ItemSpec, long> _itemSpecRepository;
        private readonly IRepository<Item, long> _itemRepository;
        private readonly IRepository<Coupon, long> _couponRepository;
        private readonly IRepository<UserWalletDetail, long> _userWalletDetailRepository;
        private readonly IRepository<Worker, long> _workerDetailRepository;
        private readonly IRepository<Commission, long> _commissionRepository;
        private readonly IRepository<StoreRegister, long> _storeRegisterRepository;
        private readonly IRepository<ItemBargain, long> _itemBargainRepository;
        private readonly IRepository<UserAddress, long> _userAddressRepository;
        private readonly IRepository<BargainItemDetails, long> _bargainItemDetailRepository;
        private readonly IRepository<LogisticsEntity, long> _logisticsEntityRepository;
        private readonly IRepository<UserPoints, long> _userPointsRepository;
        private readonly IRepository<PointRules, long> _pointRulesRepository;
        private readonly IRepository<StoreSetting, long> _storeSettingRepository;
        private readonly IRepository<ReleasePointRules, long> _releasePointRulesRepository;
        private readonly IRepository<ActiveRecord, long> _activeRecordRepository;
        public OrderManager(
            IRepository<Store> storeRepository,
            IRepository<Order, long> orderRepository,
            IRepository<OrderDetail, long> orderDetailRepository,
            IRepository<UserCommission, long> userCommisionRepository,
            IRepository<User, long> userRepository,
            IRepository<UserCoupon, long> userCouponRepository,
            IRepository<GroupOrder, long> groupOrderRepository,
            IRepository<GroupOrderDetail, long> groupOrderDetailRepository,
            IRepository<Refund, long> refundRepository,
            IRepository<UserCash, long> userCashRepository,
            IRepository<ItemSpec, long> itemSpecRepository,
            IRepository<Item, long> itemRepository,
            IRepository<Coupon, long> couponRepository,
            IRepository<UserWalletDetail, long> userWalletDetailRepository,
            IRepository<Worker, long> workerDetailRepository,
            IRepository<Commission, long> commissionRepository,
            IRepository<StoreRegister, long> storeRegisterRepository,
            IRepository<ItemBargain, long> itemBargainRepository,
            IRepository<UserAddress, long> userAddressRepository,
            IRepository<BargainItemDetails, long> bargainItemDetailRepository,
            IRepository<LogisticsEntity, long> logisticsEntityRepository,
            IRepository<UserPoints, long> userPointsRepository,
            IRepository<PointRules, long> pointRulesRepository,
            IRepository<StoreSetting, long> storeSettingRepository,
            IRepository<ReleasePointRules, long> releasePointRulesRepository,
            IRepository<ActiveRecord, long> activeRecordRepository
            )
        {
            _storeRepository = storeRepository;
            _orderRepository = orderRepository;
            _orderDetailRepository = orderDetailRepository;
            _userCommisionRepository = userCommisionRepository;
            _userRepository = userRepository;
            _userCouponRepository = userCouponRepository;
            _groupOrderRepository = groupOrderRepository;
            _groupOrderDetailRepository = groupOrderDetailRepository;
            _refundRepository = refundRepository;
            _userCashRepository = userCashRepository;
            _itemSpecRepository = itemSpecRepository;
            _itemRepository = itemRepository;
            _couponRepository = couponRepository;
            _userWalletDetailRepository = userWalletDetailRepository;
            _workerDetailRepository = workerDetailRepository;
            _commissionRepository = commissionRepository;
            _storeRegisterRepository = storeRegisterRepository;
            _itemBargainRepository = itemBargainRepository;
            _userAddressRepository = userAddressRepository;
            _logisticsEntityRepository = logisticsEntityRepository;
            _userPointsRepository = userPointsRepository;
            _pointRulesRepository = pointRulesRepository;
            _storeSettingRepository = storeSettingRepository;
            _releasePointRulesRepository = releasePointRulesRepository;
            _activeRecordRepository = activeRecordRepository;
            _bargainItemDetailRepository = bargainItemDetailRepository;
        }

        public void SetDefaultAddress(Order order, long userId)
        {
            var defaultAddress = _userAddressRepository.FirstOrDefault(x => x.IsDefault && x.UserId == userId);
            if (defaultAddress != null)
            {
                order.Receiver = defaultAddress.Receiver;
                order.ReceiverAddress = defaultAddress.ReceiverAddress;
                order.ReceiverPhone = defaultAddress.ReceiverPhone;
                order.PostalCode = defaultAddress.PostalCode;
                order.ShippingType = ShippingType.Post3H;
            }
        }

        public async Task ComputerAmountAsync(Order order)
        {
            var actualAmount = order.Amount;
            var item = await _orderDetailRepository.GetAllListAsync(x => x.OrderId == order.Id);
            var packPrice = item.Select(x => (x.ItemSpec?.Item.PackPrice ?? 0)).Sum();
            order.PackPrice = packPrice;
            actualAmount += packPrice;
            if (order.ShippingType == ShippingType.Post3H || order.ShippingType == ShippingType.Post1H)
            {
                var orderDetail = await _orderDetailRepository.GetAllListAsync(x => x.OrderId == order.Id);
                var freight = orderDetail.Select(x => x.Freight).Sum();
                order.Freight = freight;
                actualAmount += freight;
                if (order.ShippingType == ShippingType.Post1H)
                {
                    actualAmount += 10;
                }
            }
            order.ActualAmount = actualAmount;
        }

        public ItemSpec GetPositiveItemSpec(long itemSpecId)
        {
            using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete))
            {
                return _itemSpecRepository.FirstOrDefault(itemSpecId);
            }
        }

        public void QueryExpressInfo(Order order)
        {
            try
            {
                var logistics = _logisticsEntityRepository.FirstOrDefault(1);
                if (!string.IsNullOrWhiteSpace(order.ShippingNo) && logistics.Qty > 0)
                {
                    var response = ExpressContext.Instance.Query(order.ShippingNo);
                    order.ShippingLog = response;
                    order.LastShippingLogTime = DateTime.Now;
                    logistics.Qty -= 1;
                    CurrentUnitOfWork.SaveChanges();
                }
            }
            catch
            { }
        }

        public void QueryWork()
        {
            try
            {
                //物流，禁用物流
                var lastQueryTime = DateTime.Now.AddHours(-4);
                var logOrders = _orderRepository.GetAll()
                    .Where(x => x.Status == OrderStatus.Sent && x.OrderNo != null && (x.LastShippingLogTime == null || x.LastShippingLogTime < lastQueryTime))
                    .OrderBy(x => x.ShippingTime)
                    .ToList();
                logOrders.ForEach(x => QueryExpressInfo(x));
                //退款超时自动处理
                //var overTime = DateTime.Now.AddDays(-SingleUserMallConsts.OverDays);
                //var waitRefunds = _refundRepository.GetAll()
                //    .Where(x => x.Status == RefundStatus.WaitAudit && x.CreationTime < overTime)
                //    .OrderBy(x => x.CreationTime)
                //    .ToList();
                //waitRefunds.ForEach(x => RefundOverTime(x));
                //CurrentUnitOfWork.SaveChanges();
                //理财产品每天返还还利润金额
                var dividendOrders = _orderRepository.GetAll()
                    .Where(x => x.ShoppingCartType.Value == ShoppingCartType.TreeShopping && x.DividendEndTime >= DateTime.Now && x.Status >= OrderStatus.Paid && x.DividendItemStatus == DividendStatus.Ongoing)
                    .OrderBy(x => x.PayTime)
                    .ToList();
                dividendOrders.ForEach(x => DividendTime(x));
                CurrentUnitOfWork.SaveChanges();
                //退款查询
                var refunds = _refundRepository.GetAll()
                    .Where(x => x.Status >= RefundStatus.Audited && x.Status < RefundStatus.Success)
                    .OrderBy(x => x.CreationTime)
                    .ToList();
                refunds.ForEach(x => RefundQuery(x));
                CurrentUnitOfWork.SaveChanges();
                //组团超时
                var groupOrders = _groupOrderRepository.GetAll()
                    .Where(x => x.Status == GroupOrderStatus.Grouping && x.EndTime < DateTime.Now)
                    .OrderBy(x => x.BeginTime)
                    .ToList();
                groupOrders.ForEach(x => GroupOrderOverTime(x));
                CurrentUnitOfWork.SaveChanges();
                //拼单超时
                var batgainEndTime = DateTime.Now.AddDays(-SingleUserMallConsts.BargainDays);
                var bargains = _itemBargainRepository.GetAll()
                    .Where(x => x.CreationTime < batgainEndTime)
                    .ToList();
                bargains.ForEach(x => BargainOverTime(x));
                CurrentUnitOfWork.SaveChanges();
                //订单支付超时
                var limitTime = DateTime.Now.AddDays(-SingleUserMallConsts.WaitPayDays);
                var waitPayOrders = _orderRepository.GetAll()
                    .Where(x => x.Status == OrderStatus.WaitPay && x.CreationTime < limitTime)
                    .OrderBy(x => x.CreationTime)
                    .ToList();
                waitPayOrders.ForEach(x => OrderPayOverTime(x));
                CurrentUnitOfWork.SaveChanges();
                //10天自动收货
                var shippingOverTime = DateTime.Now.AddDays(-SingleUserMallConsts.OverDays);
                var waitGetOrders = _orderRepository.GetAll()
                    .Where(x => x.Status == OrderStatus.Sent && x.ShippingTime.HasValue && x.ShippingTime < shippingOverTime)
                    .OrderBy(x => x.ShippingTime)
                    .ToList();
                waitGetOrders.ForEach(x => OrderGetOverTime(x));
                CurrentUnitOfWork.SaveChanges();
                //理财产品退还本金及返还利润金额
                var orders = _orderRepository.GetAll()
                    .Where(x => x.ShoppingCartType.Value == ShoppingCartType.TreeShopping && x.DividendEndTime < DateTime.Now && x.Status >= OrderStatus.Paid && x.DividendItemStatus == DividendStatus.Ongoing)
                    .OrderBy(x=> x.Amount)
                    .ToList();
                orders.ForEach(x => TreeOrderTime(x));
                CurrentUnitOfWork.SaveChanges();
                //提现结果
                var cashes = _userCashRepository.GetAll()
                   .Where(x => x.Status == CashStatus.Processing)
                   .OrderBy(x => x.CreationTime)
                   .ToList();
                cashes.ForEach(x => CashQuery(x));

                //CurrentUnitOfWork.SaveChanges();
            }
            catch (Exception e)
            {
                Writelog(e.Message);
                Writelog(e.StackTrace);
                Writelog(e.InnerException.Message);
                throw;
            }
        }

        //用钱包支付
        public string PayByWallet(string tradeNo, decimal amount, PayType payType)
        {
            var order = _orderRepository.GetAll().Where(x => x.OrderNo == tradeNo).FirstOrDefault();
            var user = _userRepository.FirstOrDefault(order.UserId);
            if (user.UserWallet >= amount)
            {
                _userWalletDetailRepository.Insert(new UserWalletDetail
                {
                    UserId = user.Id,
                    WalletExchangeAmount = -amount,
                    WalletExchangeReason = $"用户钱包消费{amount}元，订单号{tradeNo}",
                    WalletExchangeTime = DateTime.Now,
                    WalletType = UserWalletType.Out
                });
                user.UserWallet -= amount;
                PayComplete(tradeNo, amount, payType);
            }
            else
            {
                throw new UserFriendlyException("体验金不足无法购买商品！充值请联系0871-64852528");
            }

            return "success";
        }

        //用可用体验金支付
        public string PayByCanUsePoint(string tradeNo, decimal amount, PayType payType)
        {
            var order = _orderRepository.GetAll().Where(x => x.OrderNo == tradeNo).FirstOrDefault();
            var user = _userRepository.FirstOrDefault(order.UserId);
            if (user.CanUsePoints >= amount)
            {
                _userPointsRepository.Insert(new UserPoints
                {
                    Points = -amount,
                    UserId = user.Id,
                    FromUserId = order.UserId,
                    Title = $"用户可用体验金消费{amount}元，订单号{tradeNo}",
                    Type = UserPointsType.KYTYJ,
                    Status = UserPointsStatus.Out
                });
                user.CanUsePoints -= amount;
                PayComplete(tradeNo, amount, payType);
            }
            else
            {
                throw new UserFriendlyException("您的可用体验金不足");
            }

            return "success";
        }

        //用体验金支付
        public string PayByPoint(string tradeNo, decimal amount, PayType payType)
        {
            var order = _orderRepository.GetAll().Where(x => x.OrderNo == tradeNo).FirstOrDefault();
            var user = _userRepository.FirstOrDefault(order.UserId);
            if (user.Points >= amount)
            {
                _userPointsRepository.Insert(new UserPoints
                {
                    Points = -amount,
                    UserId = user.Id,
                    FromUserId = order.UserId,
                    Title = $"用户体验金消费{amount}元，订单号{tradeNo}",
                    Type = UserPointsType.TYJ,
                    Status = UserPointsStatus.Out
                });
                user.Points -= amount;
                PayComplete(tradeNo, amount, payType);
            }
            else
            {
                throw new UserFriendlyException("您的可用体验金不足");
            }

            return "success";
        }

        public void BargainOverTime(ItemBargain itemBargain)
        {
            itemBargain.IsOver = true;
        }

        public void PayComplete(string tradeNo, decimal amount, PayType payType = PayType.WechatPay)
        {
            try
            {
                var order = _orderRepository.GetAll().Where(x => x.OrderNo == tradeNo).FirstOrDefault();
                if (order != null)
                {
                    var user = _userRepository.FirstOrDefault(order.UserId);
                    order.Status = OrderStatus.Paid;
                    order.PayTime = DateTime.Now;
                    if (order.OrderType == OrderType.Shopping)
                    {
                        var orderDetails = _orderDetailRepository.GetAllList(x => x.OrderId == order.Id);
                        if (order.ShoppingCartType == ShoppingCartType.TreeShopping)
                        {
                            CalculateTreeDividend(order, user, orderDetails);
                        }
                        if (order.BargainItemId.HasValue)
                        {
                            _bargainItemDetailRepository.Insert(new BargainItemDetails
                            {
                                BargainItemId = order.BargainItemId ?? 0,
                                UserId = order.UserId,
                                UserName = order.User.Name,
                                Avatar = order.User.Avatar,
                                Name = orderDetails.FirstOrDefault(x => x.Id == order.Id)?.ItemSpec?.Item?.Name,
                                BargainTime = order.PayTime,
                                Description = $"恭喜{order.User.Name}{order.PayTime}砍价成功,0元购买{orderDetails.FirstOrDefault()?.ItemSpec?.Item?.Name}！"
                            });
                            var bargainItem = _itemBargainRepository.FirstOrDefault(order.BargainItemId.Value);
                            bargainItem.IsOver = true;
                        }
                        if (order.IsGroup)
                        {
                            GroupOrderWork(order);
                        }
                        //CalculateUserCommission(order, user, orderDetails);
                        //销量计算
                        ItemSale(orderDetails);
                        CalculateOrderPoint(order, user, orderDetails);
                        //升级合伙人
                        if (user.VipLevel != 2 && orderDetails.FirstOrDefault().ItemSpec.Item.TreeCount> 0 && order.ActualAmount >= _storeSettingRepository.FirstOrDefault(x=> x.Id == 1).Value)
                        {
                            user.IsVip = true;
                            user.VipLevel = 2;
                            var sourceUser = _userRepository.FirstOrDefault(x => x.Id == user.SourceUserId);
                            CalculateDirectUserToSuperVIPCanGetPoint(order, user, sourceUser);
                        }
                    }
                    //else if (order.OrderType == OrderType.Register)
                    //{
                    //    user.IsVip = true;
                    //}
                    //else if (order.OrderType == OrderType.Agency)
                    //{
                    //    user.AgencyLevel = 1;
                    //    user.IsVip = true;
                    //    user.VipLevel = 1;
                    //    DivideCommmission(order, user, "代理佣金");
                    //}
                }
            }
            catch (Exception ex)
            {
                Writelog(ex.StackTrace);
            }
        }

        private void CalculateDirectUserToSuperVIPCanGetPoint(Order order, User user, User sourceUser)
        {
            if (sourceUser != null)
            {
                var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == (UserRuleLevel)sourceUser.VipLevel);
                if (pointRule != null)
                {
                    var canGetPoint = pointRule.DirectUserToSuperVIP;
                    if (canGetPoint > 0)
                    {
                        _userPointsRepository.Insert(new UserPoints
                        {
                            Points = canGetPoint,
                            UserId = sourceUser.Id,
                            FromUserId = user.Id,
                            Title = $"直推会员{user.Name}升级到合伙人 获得{canGetPoint}元体验金,订单号{order.OrderNo}",
                            Type = UserPointsType.TYJ,
                            Status = UserPointsStatus.In
                        });
                        sourceUser.Points += canGetPoint;
                    }
                }

                decimal getReleasePoints = _storeSettingRepository.FirstOrDefault(x => x.Id == 2).Value;
                if (getReleasePoints > 0)
                {
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = getReleasePoints,
                        UserId = sourceUser.Id,
                        FromUserId = user.Id,
                        Title = $"直推会员{user.Name}升级到合伙人  释放{getReleasePoints}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.KYTYJ,
                        Status = UserPointsStatus.In
                    });
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = -getReleasePoints,
                        UserId = sourceUser.Id,
                        FromUserId = user.Id,
                        Title = $"直推会员{user.Name}升级到合伙人  释放{getReleasePoints}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.TYJ,
                        Status = UserPointsStatus.Out
                    });
                    sourceUser.CanUsePoints += getReleasePoints;
                    sourceUser.Points -= getReleasePoints;
                    var releasePointRule = _releasePointRulesRepository.FirstOrDefault(1);
                    CheckUserIsSuperVIPAndRelease(sourceUser, getReleasePoints, releasePointRule, order);
                }
            }
        }

        public void CalculateDirectUserToVIPCanGetPoint(User user, User sourceUser)
        {
            if (sourceUser != null && sourceUser.IsVip)
            {
                var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == (UserRuleLevel)sourceUser.VipLevel);
                if (pointRule != null)
                {
                    var canGetPoint = pointRule.DirectUserToVIP;
                    if (canGetPoint > 0)
                    {
                        _userPointsRepository.Insert(new UserPoints
                        {
                            Points = canGetPoint,
                            UserId = sourceUser.Id,
                            FromUserId = user.Id,
                            Title = $"直推会员{user.Name}升级到VIP 获得{canGetPoint}元体验金",
                            Type = UserPointsType.TYJ,
                            Status = UserPointsStatus.In
                        });
                        sourceUser.Points += canGetPoint;
                    }
                }
            }
        }

        public void CalculateDirectUserToNormalCanGetPoint(User user, User sourceUser)
        {
            if (sourceUser != null)
            {
                var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == (UserRuleLevel)sourceUser.VipLevel);
                if (pointRule != null)
                {
                    var canGetPoint = pointRule.SharePoint;
                    if (canGetPoint > 0)
                    {
                        _userPointsRepository.Insert(new UserPoints
                        {
                            Points = canGetPoint,
                            UserId = sourceUser.Id,
                            FromUserId = user.Id,
                            Title = $"分享链接给会员{user.Name}注册 获得{canGetPoint}元体验金",
                            Type = UserPointsType.TYJ,
                            Status = UserPointsStatus.In
                        });
                        sourceUser.Points += canGetPoint;
                    }
                }
            }
        }

        public void CheckUserIsSuperVIPAndRelease(User user, decimal amount, ReleasePointRules releasePointRule, Order order)
        {
            if(user.IsVip && user.VipLevel == 2)
            {
                var sourceUser = _userRepository.FirstOrDefault(x => x.Id == user.SourceUserId);
                if(sourceUser != null)
                {
                    var rate = sourceUser.IsVip ? (sourceUser.VipLevel == 1 ? releasePointRule.DirectSuperVIPUserToVIPRate : releasePointRule.DirectSuperVIPUserToSuperVIPRate) : releasePointRule.DirectSuperVIPUserToNormalUserRate;
                    decimal getReleasePoints = Decimal.Parse(((double)amount * rate).ToString());
                    if (getReleasePoints > 0)
                    {
                        _userPointsRepository.Insert(new UserPoints
                        {
                            Points = getReleasePoints,
                            UserId = sourceUser.Id,
                            FromUserId = user.Id,
                            Title = $"直推合伙人{user.Name}, 释放{getReleasePoints}元体验金,订单号{order.OrderNo}",
                            Type = UserPointsType.KYTYJ,
                            Status = UserPointsStatus.In
                        });
                        _userPointsRepository.Insert(new UserPoints
                        {
                            Points = -getReleasePoints,
                            UserId = sourceUser.Id,
                            FromUserId = user.Id,
                            Title = $"直推合伙人{user.Name}, 释放{getReleasePoints}元体验金,订单号{order.OrderNo}",
                            Type = UserPointsType.TYJ,
                            Status = UserPointsStatus.Out
                        });
                        sourceUser.CanUsePoints += getReleasePoints;
                        sourceUser.Points -= getReleasePoints;
                    }
                }
            }
        }



        private void CalculateOrderPoint(Order order, User user, List<OrderDetail> orderDetails)
        {
            var getPoints = orderDetails.Select(x => x.ItemSpec.Item.Points * x.Qty).Sum();
            ReleasePointRules releasePointRule = null;
            if (orderDetails.FirstOrDefault().ItemSpec.Item.IsReleasePoints)
            {
                releasePointRule = _releasePointRulesRepository.FirstOrDefault(orderDetails.FirstOrDefault().ItemSpec.Item.ReleasePointId);
            }
            var sourceUser = _userRepository.FirstOrDefault(x => x.Id == user.SourceUserId);
            if (getPoints > 0)
            {
                _userPointsRepository.Insert(new UserPoints
                {
                    Points = getPoints,
                    UserId = user.Id,
                    FromUserId = user.Id,
                    Title = $"消费￥{order.ActualAmount}元,获得{getPoints}元体验金,订单号{order.OrderNo}",
                    Type = UserPointsType.TYJ,
                    Status = UserPointsStatus.In
                });
                user.Points += getPoints;
            }
            if (releasePointRule != null && order.PayType != PayType.PointPay)
            {
                var rate = user.IsVip ? (user.VipLevel == 1 ? releasePointRule.VIPUserOwnBuyRate : releasePointRule.SuperVIPUserOwnBuyRate) : releasePointRule.NormalUserOwnBuyRate;
                decimal getReleasePoints = Decimal.Parse(((double)order.ActualAmount * rate).ToString());
                if (getReleasePoints > 0)
                {
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = getReleasePoints,
                        UserId = user.Id,
                        FromUserId = user.Id,
                        Title = $"消费￥{order.ActualAmount}元, 释放{getReleasePoints}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.KYTYJ,
                        Status = UserPointsStatus.In
                    });
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = -getReleasePoints,
                        UserId = user.Id,
                        FromUserId = user.Id,
                        Title = $"消费￥{order.ActualAmount}元, 释放{getReleasePoints}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.TYJ,
                        Status = UserPointsStatus.Out
                    });
                    user.CanUsePoints += getReleasePoints;
                    user.Points -= getReleasePoints;
                    CheckUserIsSuperVIPAndRelease(user, getReleasePoints, releasePointRule, order);
                }
            }
            if (sourceUser != null)
            {
                if(sourceUser.IsVip && !user.IsVip)
                {
                    if(sourceUser.VipLevel == 1)
                    {
                        if(getPoints > 0)
                        {
                            var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == UserRuleLevel.VIPUser);
                            CalculateCanGetDirectUserPointByOrder(order, user, getPoints, sourceUser, pointRule, releasePointRule);
                        }
                    }
                    else
                    {
                        if(getPoints > 0)
                        {
                            var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == UserRuleLevel.SuperVIPUser);
                            CalculateCanGetDirectUserPointByOrder(order, user, getPoints, sourceUser, pointRule, releasePointRule);
                        }
                    }
                }
                if(user.IsVip && user.VipLevel == 1)
                {
                    if(getPoints > 0)
                    {
                        CalculateCanGetVIPGroupPointByOrder(order, user, getPoints, releasePointRule);
                    }
                }
            }
        }

        public void CalculateSignOrActivePoint(User user, decimal amount, string message, User sourceUser)
        {
            if (sourceUser.IsVip && !user.IsVip)
            {
                if (sourceUser.VipLevel == 1)
                {
                    var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == UserRuleLevel.VIPUser);
                    CalculateCanGetDirectUserPointBySignOrActive(user, amount, sourceUser, pointRule, message);
                }
                else
                {
                    var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == UserRuleLevel.SuperVIPUser);
                    CalculateCanGetDirectUserPointBySignOrActive(user, amount, sourceUser, pointRule, message);
                }
            }
            if (user.IsVip && user.VipLevel == 1)
            {
                CalculateCanGetVIPGroupPointBySignOrActive(user, amount, message);
            }
        }

        public void CalculateCanGetDirectUserPointBySignOrActive(User user, decimal getPoints, User sourceUser, PointRules pointRule, string message)
        {
            decimal canGetPoint = getPoints * pointRule.DirectUserRate;
            if (canGetPoint > 0)
            {
                _userPointsRepository.Insert(new UserPoints
                {
                    Points = canGetPoint,
                    UserId = sourceUser.Id,
                    FromUserId = user.Id,
                    Title = $"直推会员{user.Name}的返利 获得{canGetPoint}元体验金,来源{message}",
                    Type = UserPointsType.TYJ,
                    Status = UserPointsStatus.In
                });
                sourceUser.Points += canGetPoint;
            }

        }

        private void CalculateCanGetDirectUserPointByOrder(Order order, User user, decimal getPoints, User sourceUser, PointRules pointRule, ReleasePointRules releasePointRule)
        {
            decimal canGetPoint = getPoints * pointRule.DirectUserRate;
            if(canGetPoint > 0)
            {
                _userPointsRepository.Insert(new UserPoints
                {
                    Points = canGetPoint,
                    UserId = sourceUser.Id,
                    FromUserId = user.Id,
                    Title = $"直推会员{user.Name}的返利 获得{canGetPoint}元体验金,订单号{order.OrderNo}",
                    Type = UserPointsType.TYJ,
                    Status = UserPointsStatus.In
                });
                sourceUser.Points += canGetPoint;
            }

            if(releasePointRule != null && order.PayType != PayType.PointPay)
            {
                var releaseRate = sourceUser.VipLevel
                     == 1 ? releasePointRule.DirectNormalUserToVIPRate : releasePointRule.DirectNormalUserToSuperVIPRate;
                decimal releasePoint = Decimal.Parse(((double)order.ActualAmount * releaseRate).ToString());
                if (releasePoint > 0)
                {
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = releasePoint,
                        UserId = sourceUser.Id,
                        FromUserId = order.UserId,
                        Title = $"直推会员{user.Name}消费￥{order.ActualAmount}元, 释放{releasePoint}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.KYTYJ,
                        Status = UserPointsStatus.In
                    });
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = -releasePoint,
                        UserId = sourceUser.Id,
                        FromUserId = order.UserId,
                        Title = $"直推会员{user.Name}消费￥{order.ActualAmount}元, 释放{releasePoint}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.TYJ,
                        Status = UserPointsStatus.Out
                    });
                    sourceUser.CanUsePoints += releasePoint;
                    sourceUser.Points -= releasePoint;
                    CheckUserIsSuperVIPAndRelease(sourceUser, releasePoint, releasePointRule, order);
                }
            }
        }

        public void CalculateCanGetVIPGroupPointBySignOrActive(User user, decimal getPoints, string message)
        {
            var superVIPUser = GetSuperVIPUserByVIPGroup(user);
            if (superVIPUser != null && superVIPUser.VipLevel == 2)
            {
                var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == UserRuleLevel.SuperVIPUser);
                decimal canGetPoint = getPoints * pointRule.VIPGroupRate;
                if (canGetPoint > 0)
                {
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = canGetPoint,
                        UserId = superVIPUser.Id,
                        FromUserId = user.Id,
                        Title = $"下级VIP团队{user.Name}返利 获得{canGetPoint}元体验金,来源{message}",
                        Type = UserPointsType.TYJ,
                        Status = UserPointsStatus.In
                    });
                    superVIPUser.Points += canGetPoint;
                }
            }
        }


        private void CalculateCanGetVIPGroupPointByOrder(Order order, User user, decimal getPoints, ReleasePointRules releasePointRule)
        {
            var superVIPUser = GetSuperVIPUserByVIPGroup(user);
            if(superVIPUser != null && superVIPUser.VipLevel == 2)
            {
                var pointRule = _pointRulesRepository.FirstOrDefault(x => x.UserRuleLevel == UserRuleLevel.SuperVIPUser);
                decimal canGetPoint = getPoints * pointRule.VIPGroupRate;
                if (canGetPoint > 0)
                {
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = canGetPoint,
                        UserId = superVIPUser.Id,
                        FromUserId = user.Id,
                        Title = $"下级VIP团队{user.Name}返利 获得{canGetPoint}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.TYJ,
                        Status = UserPointsStatus.In
                    });
                    superVIPUser.Points += canGetPoint;
                }

                decimal releasePoint = Decimal.Parse(((double)getPoints * releasePointRule.DirectVIPGroupUserToSuperVIPRate).ToString());
                if (releasePoint > 0 && order.PayType != PayType.PointPay)
                {
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = releasePoint,
                        UserId = superVIPUser.Id,
                        FromUserId = user.Id,
                        Title = $"下级VIP团队{user.Name}消费￥{order.ActualAmount}元, 释放{releasePoint}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.KYTYJ,
                        Status = UserPointsStatus.In
                    });
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = -releasePoint,
                        UserId = superVIPUser.Id,
                        FromUserId = user.Id,
                        Title = $"下级VIP团队{user.Name}消费￥{order.ActualAmount}元, 释放{releasePoint}元体验金,订单号{order.OrderNo}",
                        Type = UserPointsType.TYJ,
                        Status = UserPointsStatus.Out
                    });
                    superVIPUser.CanUsePoints += releasePoint;
                    superVIPUser.Points -= releasePoint;
                    CheckUserIsSuperVIPAndRelease(superVIPUser, releasePoint, releasePointRule, order);
                }
            }
        }

        private User GetSuperVIPUserByVIPGroup(User user)
        {
            if (user == null || user.VipLevel == 2)
            {
                return user;
            }
            else
            {
                var superVIPUser = _userRepository.FirstOrDefault(x => x.Id == user.SourceUserId);
                return GetSuperVIPUserByVIPGroup(superVIPUser);
            }
        }

        private void CalculateTreeDividend(Order order, User user, List<OrderDetail> orderDetails)
        {
            var item = _itemRepository.FirstOrDefault(x => x.Id == order.ItemId && x.ItemType == Item.ItemsType.DividendItems);
            order.DividendEndTime = order.PayTime.Value.AddMonths(item.Timelimit.Value);
            order.DividendItemStatus = DividendStatus.Ongoing;
            //分红多少天
            TimeSpan dividendDay = order.DividendEndTime.Value.Subtract(order.PayTime.Value).Duration();
            var orderDetail = order.OrderDetails.FirstOrDefault();
            item.TreeRemainingQty -= orderDetail.Qty;
            var totalProfit = orderDetail.ItemSpec.Item.DividendAmount * order.ActualAmount;
            orderDetail.Profit = 0;
            orderDetail.DailyProfit = totalProfit / dividendDay.Days;
            orderDetail.DividendDay = 0;
            _orderRepository.UpdateAsync(order);
            user.SumConsumptionAmount += order.ActualAmount;
            user.SumDividendAmount += orderDetails.FirstOrDefault(x => x.Id == order.Id)?.ItemSpec?.Item?.DividendAmount * order.ActualAmount ?? 0;
        }

        private void CalculateUserCommission(Order order, User user, List<OrderDetail> orderDetails)
        {
            var commission = _commissionRepository.GetAll().FirstOrDefault();
            //用户
            if (user.SourceUserId.HasValue)
            {
                var sourceOneUser = _userRepository.FirstOrDefault(user.SourceUserId.Value);
                //是推广大使
                //一级分销拿到的钱
                if (sourceOneUser != null)
                {
                    decimal firstAmount = order.ActualAmount * commission.FirstCommission;
                    _userCommisionRepository.Insert(new UserCommission
                    {
                        Amount = firstAmount,
                        UserId = user.SourceUserId.Value,
                        FromUserId = order.UserId,
                        ItemName = orderDetails.FirstOrDefault()?.ItemSpec?.Item?.Name,
                        CommissionType = (CommissionType)order.ShoppingCartType.Value
                    });
                    sourceOneUser.Commision += firstAmount;
                }
            }
            if (user.GrandUserId.HasValue)
            {
                //获取二级分销
                var sourceTwoUser = _userRepository.FirstOrDefault(user.GrandUserId.Value);
                //二级分销拿到的钱
                if (sourceTwoUser != null)
                {
                    decimal secondAmount = order.ActualAmount * commission.SecondCommission;
                    _userCommisionRepository.Insert(new UserCommission
                    {
                        Amount = secondAmount,
                        UserId = sourceTwoUser.Id,
                        FromUserId = order.UserId,
                        ItemName = orderDetails.FirstOrDefault()?.ItemSpec?.Item?.Name,
                        CommissionType = (CommissionType)order.ShoppingCartType.Value
                    });
                    sourceTwoUser.Commision += secondAmount;
                }
            }
        }

        private void DivideCommmission(Order order, User user, string name)
        {
            if (user.SourceUserId.HasValue && order.PayType != PayType.WalletPay)
            {
                var sourceOneUser = _userRepository.FirstOrDefault(user.SourceUserId.Value);
                var commission = _commissionRepository.FirstOrDefault(x => x.Id == 1);
                //是推广大使
                //一级分销拿到的钱
                if (sourceOneUser != null)
                {
                    decimal firstAmount = order.ActualAmount * commission.FirstCommission;
                    _userCommisionRepository.Insert(new UserCommission
                    {
                        Amount = firstAmount,
                        UserId = user.SourceUserId.Value,
                        FromUserId = order.UserId,
                        ItemName = name
                    });
                    sourceOneUser.Commision += firstAmount;
                    if (user.GrandUserId.HasValue)
                    {
                        //获取二级分销
                        var sourceTwoUser = _userRepository.FirstOrDefault(user.GrandUserId.Value);
                        //二级分销拿到的钱
                        if (sourceTwoUser != null)
                        {
                            decimal secondAmount = order.ActualAmount * commission.SecondCommission;
                            _userCommisionRepository.Insert(new UserCommission
                            {
                                Amount = secondAmount,
                                UserId = sourceTwoUser.Id,
                                FromUserId = order.UserId,
                                ItemName = name
                            });
                            sourceTwoUser.Commision += secondAmount;
                        }
                    }
                }
            }
        }

        public static void Writelog(string msg)
        {
            StreamWriter stream;
            //写入日志内容
            string path = AppDomain.CurrentDomain.BaseDirectory;
            //检查上传的物理路径是否存在，不存在则创建
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            stream = new StreamWriter(path + "\\log.txt", true, Encoding.Default);
            stream.Write(DateTime.Now.ToString() + ":" + msg);
            stream.Write("\r\n");
            stream.Flush();
            stream.Close();
        }

        public void GroupOrderWork(Order order)
        {
            var groupOrderDetail = _groupOrderDetailRepository.FirstOrDefault(x => x.OrderId == order.Id);
            if (groupOrderDetail != null)
            {
                groupOrderDetail.IsValid = true;
                var groupOrder = _groupOrderRepository.FirstOrDefault(groupOrderDetail.GroupOrderId);
                groupOrder.PartinCount = _groupOrderDetailRepository.Count(x => x.GroupOrderId == groupOrder.Id && x.IsValid && x.Id != groupOrderDetail.Id) + 1;
                if (groupOrder.Status == GroupOrderStatus.Init)
                {
                    groupOrder.Status = GroupOrderStatus.Grouping;
                }
                if (groupOrder.Status == GroupOrderStatus.Grouping)
                {
                    if (groupOrder.PartinCount >= groupOrder.TotalCount)
                    {
                        groupOrder.Status = GroupOrderStatus.Success;
                        order.Status = OrderStatus.Group;
                        var orders = _groupOrderDetailRepository.GetAll().Where(x => x.GroupOrderId == groupOrder.Id && x.IsValid && x.Id != groupOrderDetail.Id).Select(x => x.Order).ToList();
                        orders.ForEach(x =>
                        {
                            x.Status = OrderStatus.Group;
                        });
                    }
                }
            }
        }

        public void ItemSale(List<OrderDetail> orderDetails)
        {
            var monthDate = DateTime.Now.AddMonths(-1);
            orderDetails.ForEach((Action<OrderDetail>)(x =>
            {
                var itemId = x.ItemSpec.ItemId;
                var item = _itemRepository.FirstOrDefault(itemId);
                var store = this._storeRepository.FirstOrDefault((Store y) => y.Id == item.StoreId);
                item.TotalSale += x.Qty;
                if(item.TreeCount > 0)
                {
                    item.LeftTreeCount -= x.Qty;
                }
                store.StoreTotalSale += x.Qty;
                item.MonthSale = (from i in _orderDetailRepository.GetAll()
                                  where i.ItemSpec.ItemId == itemId && i.CreationTime > monthDate && i.Order.Status > OrderStatus.Paid
                                  select (int?)i.Qty).Sum() ?? 0;
            }));
        }

        //计算商城评价
        public void CalculateStoreStar(long itemId, int star)
        {
            var item = _itemRepository.FirstOrDefault(x => x.Id == itemId);
            var store = _storeRepository.FirstOrDefault(x => x.Id == item.StoreId);
            if (store.StoreStar == 0)
            {
                store.StoreStar = star;
            }
            else
            {
                store.StoreStar = 5;
            }
        }

        public void GroupOrderOverTime(GroupOrder order)
        {
            order.Status = GroupOrderStatus.Cancel;
            var orders = (from i in _orderRepository.GetAll()
                          join d in _groupOrderDetailRepository.GetAll() on i.Id equals d.OrderId
                          where d.GroupOrderId == order.Id
                          orderby i.CreationTime
                          select i).ToList();
            orders.ForEach(x =>
            {
                var refund = new Refund
                {
                    Amount = x.ActualAmount,
                    Reason = "超时取消团购，自动退款",
                    Type = RefundType.RefundMoney,
                    Status = RefundStatus.Audited,
                    RefundTime = DateTime.Now,
                    RefundNo = Functions.NewOrderNo(),
                    PhoneNumber = x.ReceiverPhone,
                    OrderId = x.Id,
                    OrderDetailId = x.OrderDetails.First().Id,
                };
                var refundId = _refundRepository.InsertAndGetId(refund);
                CurrentUnitOfWork.SaveChanges();
                refund = _refundRepository.FirstOrDefault(refundId);
                Refund(x, refund);
            });
        }
        public void TreeOrderTime(Order order)
        {
            //order.Status = OrderStatus.Cancel;
            //var orders = (from i in _orderRepository.GetAll()
            //              join d in _orderDetailRepository.GetAll() on i.Id equals d.OrderId
            //              where d.OrderId == order.Id && i.ShoppingCartType.Value == ShoppingCartType.TreeShopping
            //              orderby i.CreationTime
            //              select i).ToList();
            //orders.ForEach(x =>
            //{
            //    var refund = new Refund
            //    {
            //        Amount = x.ActualAmount,
            //        Reason = "理财产品期限已到，自动退款本金及返还理财产品获利金额",
            //        Type = RefundType.RefundMoney,
            //        Status = RefundStatus.Audited,
            //        RefundTime = DateTime.Now,
            //        RefundNo = Functions.NewOrderNo(),
            //        PhoneNumber = x.ReceiverPhone,
            //        Profit = x.OrderDetails.FirstOrDefault()?.ItemSpec?.Item?.DividendAmount * x.ActualAmount ?? 0,
            //        OrderId = x.Id,
            //        OrderDetailId = x.OrderDetails.First().Id,
            //    };
            //    var refundId = _refundRepository.InsertAndGetId(refund);
            //    CurrentUnitOfWork.SaveChanges();
            //    refund = _refundRepository.FirstOrDefault(refundId);
            //    Refund(x, refund);
            //});
            var x = order;
            var refund = _refundRepository.FirstOrDefault(n => n.OrderId == x.Id);
            if (refund == null)
            {
                refund = new Refund
                {
                    Amount = x.ActualAmount,
                    Reason = "理财产品期限已到，自动退款本金及返还理财产品获利金额",
                    Type = RefundType.RefundMoney,
                    Status = RefundStatus.Audited,
                    RefundTime = DateTime.Now,
                    RefundNo = Functions.NewOrderNo(),
                    PhoneNumber = x.ReceiverPhone,
                    Profit = x.OrderDetails.FirstOrDefault()?.ItemSpec?.Item?.DividendAmount * x.ActualAmount ?? 0,
                    OrderId = x.Id,
                    OrderDetailId = x.OrderDetails.First().Id,
                };
                var refundId = _refundRepository.InsertAndGetId(refund);
                CurrentUnitOfWork.SaveChanges();
                refund = _refundRepository.FirstOrDefault(refundId);
            }
            Refund(x, refund, true);
            x.DividendItemStatus = DividendStatus.End;
        }


        public void OrderPayOverTime(Order order)
        {
            order.Status = OrderStatus.Cancel;
        }


        //将店铺设置为非法 下架所有商品
        public void StoreGetOverTime(Store store)
        {
            store.IsInvalid = true;
            var items = _itemRepository.GetAll().Where(x => x.StoreId == store.Id && x.IsSale).ToList();
            items.ForEach(item =>
            {
                item.IsSale = false;
            });
        }

        public void OrderGetOverTime(Order order)
        {
            using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete))
            {
                order.Status = OrderStatus.Successed;
                order.ReceiveTime = DateTime.Now;
            }
        }
        public void DividendTime(Order order)
        {
            var date = System.DateTime.Now;
            order.OrderDetails.ToList().ForEach((x =>
            {
                if (x.ProfitDateTime.HasValue && x.ProfitDateTime.Value.Day == date.Day)
                {
                    return;
                }
                if (x.DailyProfit > 0)
                {
                    x.DividendDay += 1;
                    x.Profit += x.DailyProfit;
                    x.ProfitDateTime = date;
                    x.IsProfitStart = true;
                    if (!order.IsFriend)
                    {
                        _userCommisionRepository.Insert(new UserCommission
                        {
                            Amount = x.DailyProfit.Value,
                            UserId = order.User.Id,
                            FromUserId = order.User.Id,
                            ItemName = x.ItemSpec.Item.Name,
                            CommissionType = CommissionType.TreeShopping
                        });
                        order.User.Commision += x.DailyProfit.Value;
                    }
                    else
                    {
                        var friend = _userRepository.FirstOrDefault(order.FriendUserId.Value);
                        if (friend != null)
                        {
                            _userCommisionRepository.Insert(new UserCommission
                            {
                                Amount = x.DailyProfit.Value,
                                UserId = friend.Id,
                                FromUserId = order.User.Id,
                                ItemName = x.ItemSpec.Item.Name,
                                CommissionType = CommissionType.TreeShopping
                            });
                            friend.Commision += x.DailyProfit.Value;
                        }
                    }

                }
            }));
        }

        public void RefundOverTime(Refund refund)
        {
            refund.Status = RefundStatus.Audited;
            refund.CloseReason = "退款超时，系统自动处理";
            refund.RefundTime = DateTime.Now;
            Refund(refund.Order, refund);
        }

        public void Refund(long id)
        {
            var refund = _refundRepository.FirstOrDefault(id);
            Refund(refund.Order, refund, true);
        }

        public void Refund(Order order, Refund refund, bool isThrow = false)
        {
            var user = _userRepository.FirstOrDefault(order.UserId);
            var orderDetail = _orderDetailRepository.FirstOrDefault(x => x.OrderId == order.Id && x.Id == refund.OrderDetailId);
            try
            {
                if (order.PayType == PayType.WechatAppPay)
                {
                    WxPayContext.H5Instance.Refund(order.OrderNo, refund.RefundNo, order.ActualAmount, refund.Amount, refund.Remark);
                }
                else if (order.PayType == PayType.WechatPay)
                {
                    WxPayContext.H5Instance.Refund(order.OrderNo, refund.RefundNo, order.ActualAmount, refund.Amount, refund.Remark);
                }
                else if (order.PayType == PayType.AliPay)
                {
                    AliPayContext.Instance.RefundOrder(order.OrderNo, refund.RefundNo, refund.Amount.ToString());
                }
                else if (order.PayType == PayType.WalletPay)
                {
                    _userWalletDetailRepository.Insert(new UserWalletDetail
                    {
                        UserId = order.UserId,
                        WalletExchangeAmount = refund.Amount,
                        WalletExchangeReason = $"退款 用户钱包返还{refund.Amount}元，订单号{order.OrderNo}",
                        WalletExchangeTime = DateTime.Now,
                        WalletType = UserWalletType.In
                    });
                    user.UserWallet += refund.Amount;
                }
                else if (order.PayType == PayType.CanUsedPointPay)
                {
                    _userPointsRepository.Insert(new UserPoints
                    {
                        Points = refund.Amount,
                        UserId = user.Id,
                        FromUserId = order.UserId,
                        Title = $"退款 用户可用体验金返还{refund.Amount}元，订单号{order.OrderNo}",
                        Type = UserPointsType.KYTYJ,
                        Status = UserPointsStatus.In
                    });
                    user.CanUsePoints += refund.Amount;
                }
                orderDetail.IsRefund = true;
                CurrentUnitOfWork.SaveChanges();
                if (order.OrderDetails.Count(x => !x.IsRefund) == 0 && (order.IsGroup || order.ShoppingCartType == ShoppingCartType.ShoppingItems))
                {
                    order.Status = OrderStatus.Cancel;
                }
            }
            catch (Exception ex)
            {
                refund.ErrorMessage = ex.Message;
                if (isThrow)
                {
                    throw ex;
                }
            }
        }

        public void RefundQuery(Refund refund)
        {
            using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete))
            {
                try
                {
                    RefunStatus status = RefunStatus.Init;
                    if (refund.Order.PayType == PayType.WechatAppPay)
                    {
                        status = WxPayContext.H5Instance.RefundQuery(refund.RefundNo);
                    }
                    else if (refund.Order.PayType == PayType.WechatPay)
                    {
                        status = WxPayContext.H5Instance.RefundQuery(refund.RefundNo);
                    }
                    else if (refund.Order.PayType == PayType.AliPay)
                    {
                        status = AliPayContext.Instance.RefundQuery(refund.RefundNo, refund.Order.OrderNo);

                    }
                    Writelog("状态" + status.ToString());
                    switch (status)
                    {
                        case RefunStatus.SUCCESS:
                            refund.Status = RefundStatus.Success;
                            var store = _storeRepository.FirstOrDefault((Store y) => y.Id == refund.OrderDetail.ItemSpec.Item.StoreId);
                            int qty = refund.OrderDetail.Qty;
                            decimal price = refund.OrderDetail.Price;
                            store.StoreTotalSale -= qty;
                            break;
                        case RefunStatus.REFUNDCLOSE:
                            refund.Status = RefundStatus.Close;
                            break;
                        case RefunStatus.PROCESSING:
                            refund.Status = RefundStatus.Processing;
                            break;
                        default:
                            refund.Status = RefundStatus.Error;
                            break;
                    }
                }
                catch (Exception ex)
                {
                    refund.ErrorMessage = ex.Message;
                }
            }
        }

        public void CashQuery(UserCash userCash)
        {
            try
            {
                var status = WxPayContext.H5Instance.PayBankResult(userCash.OrderNo);
                userCash.Status = status;
            }
            catch (Exception ex)
            {
                userCash.ErrorMessage = ex.Message;
            }
        }
    }
}
